import 'package:flutter/material.dart';

class TabBarControllerPage extends StatefulWidget {
  TabBarControllerPage({Key? key}) : super(key: key);

  @override
  _TabBarControllerPageState createState() => _TabBarControllerPageState();
}

class _TabBarControllerPageState extends State<TabBarControllerPage>
    with SingleTickerProviderStateMixin {
  //这个需要在initState里赋值，因为需要this变量
  late TabController _tabController;

  //initState dispose是两个生命周期函数
  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);
    //tab bar的响应回调
    _tabController.addListener(() {
      print(_tabController.index);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('TabBarControllerPage'),
          bottom: TabBar(
            tabs: [Tab(text: "abc"), Tab(text: "cba")],
            controller: this._tabController,
          ),
        ),
        body: TabBarView(
          controller: this._tabController,
          children: [Center(child: Text("abc")), Center(child: Text("cba"))],
        ));
  }
}
